import random
import os
import shelve
import shutil
import ctypes
from datetime import datetime

from tkinter import *
from tkinter.scrolledtext import ScrolledText
from tkinter.ttk import *
from tkinter.filedialog import askopenfilename
from tkinter.messagebox import *
from functools import partial

from base_event import CEvent
from base_screen import BigScreen, build_pos, is_2d_array
import pygame


class MyConfigApp(Tk):
    """继承Tk，创建自己的桌面应用程序类"""

    def __init__(self):
        """构造函数"""
        super().__init__()
        self.logs = None
        self.title('控制台')
        self.geometry('600x600+100+100')

        self.the_title = StringVar()
        self.names = StringVar()

        self.lun_count = IntVar()
        self.names_per_lun = IntVar()
        self.names_per_line = IntVar()

        self.init_ui()
        self.init_data()

    def init_ui(self):
        """初始化界面"""
        root = self
        max_cols = 2
        # top_frame = Frame(root)
        # bottom_left_frame = Frame(root)
        # bottom_right_frame = Frame(root)
        #
        # top_frame.grid(row=0, column=0, columnspan=max_cols, sticky="nsew")  # 填充整个单元格
        # bottom_left_frame.grid(row=1, column=0, columnspan=int(max_cols / 2), sticky="nsew")  # 跨两列
        # bottom_right_frame.grid(row=1, column=1, columnspan=int(max_cols / 2), sticky="nsew")  # 跨两列
        #
        # # 设置列的权重
        # root.grid_columnconfigure(0, weight=1)
        # root.grid_columnconfigure(1, weight=1)  # 第二列的权重更大，因此它将占据更多空间
        #
        # # 设置行的权重
        # root.grid_rowconfigure(0, weight=1)
        # root.grid_rowconfigure(1, weight=1)  # 第一行权重更大，占据更多空间

        buttons = ['开始抽取', '全新开始', '导出结果', '关于']

        # root = bottom_left_frame
        root.grid_columnconfigure(0, weight=1)
        root.grid_columnconfigure(1, weight=1)  # 第二列的权重更大，因此它将占据更多空间
        root.grid_columnconfigure(2, weight=1)  # 第二列的权重更大，因此它将占据更多空间
        root.grid_columnconfigure(3, weight=1)  # 第二列的权重更大，因此它将占据更多空间
        root.grid_rowconfigure(5, weight=1)

        labels = ['请输入标题：', '上传名单：', '总轮次：', '每轮选中人数：', ]
        for i in range(len(labels)):
            l = Label(root, text=labels[i])
            l.grid(row=i, column=0, columnspan=1, sticky='w')
        for i in range(len(buttons)):
            b = Button(root, text=buttons[i], command=partial(self.callback, buttons[i]))
            b.grid(row=len(labels), column=i, columnspan=1, sticky='w')
            # b.pack(side=LEFT, expand=True, fill=X)

        values = [self.the_title, self.names]
        for i in range(len(values)):
            Entry(root, textvariable=values[i]).grid(row=i, column=1, columnspan=2, sticky="nsew")
            if i > 0:
                Button(root, text='上传', command=partial(self.callback, labels[i])).grid(row=i, column=3, sticky="w")

        values = [self.lun_count, self.names_per_lun]
        for i in range(len(values)):
            Spinbox(root, textvariable=values[i], from_=0, to=99).grid(row=i + 2, column=1, columnspan=2, sticky="nsew")

        text_box = Text(root)
        text_box.grid(row=1 + len(labels), column=0, columnspan=4, sticky='nsew')
        # content = ""
        with open('assets/使用说明.txt', 'r', encoding='utf-8') as f:
            for l in f.readlines():
                text_box.insert('end', l)
        text_box.insert('end', '复杂抽取规则、内定部分名单等更多个性化定制需求请向公众号“东凤莱仪”留言或发邮件到dongfenglaiyi@foxmail.com')
        text_box.config(state='disabled')

    def init_data(self):
        db = shelve.open('assets/game_init.db')
        the_title = db.get('the_title', '')
        names = db.get('names', '')
        lun_count = db.get('lun_count', 1)
        names_per_lun = db.get('names_per_lun', 1)
        names_per_line = db.get('names_per_line', 1)
        db.close()
        self.the_title.set(the_title)
        self.names.set(names)
        self.lun_count.set(lun_count)
        self.names_per_lun.set(names_per_lun)
        self.names_per_line.set(names_per_line)

    def save_data(self):
        db = shelve.open('assets/game_init.db')

        db['the_title'] = self.the_title.get()
        db['names'] = self.names.get()
        db['lun_count'] = self.lun_count.get()
        db['names_per_lun'] = self.names_per_lun.get()
        db['names_per_line'] = self.names_per_line.get()
        db.close()

    def callback(self, param):
        match param:
            case '关于':
                showinfo(title='Hi', message='v1.0\n如有建议请\n向公众号“东凤莱仪”留言\n或发邮件到dongfenglaiyi@foxmail.com')
                pass
            case '上传名单：':
                print('上传名单：')
                file_path = askopenfilename(filetypes=[('TXT', '*.txt')])
                self.names.set(file_path)
            case '开始抽取':
                print('开始抽取')
                self.start_game()
            case '导出结果':
                print('导出结果')
                self.output_names()
            case '全新开始':
                print('全新开始')
                self.save_data()
                self.clean_game()
                self.start_game()

        print(f"Callback called with parameter: {param}")

    def showlog(self, text):
        # self.logs.insert(END, str(text) + "\n")
        # self.logs.update()
        print(text)

    def up_names(self):
        """点击按钮事件的响应函数, evt是事件对象"""
        file_path = askopenfilename(filetypes=[('TXT', '*.txt'), ('All Files', '*')])
        self.showlog(file_path)
        self.showlog('file_path')
        pass

    def start_game(self):
        self.save_data()
        App(self.the_title.get()).on_execute()
        pass

    def clean_game(self):
        db = shelve.open('assets/game_result.db')
        db['gamer'] = AppGamer()
        db.close()
        pass

    def output_names(self):
        try:
            db = shelve.open('assets/game_result.db')
            gamer = db.get('gamer', None)
            db.close()
            lines = []
            file = open("抽取名单.txt", 'w', encoding='utf-8')
            for i in range(1,gamer.current_lun):
                print('第%d轮' % i)
                print('\t'.join(gamer.name_luck[(i-1)*gamer.names_per_lun:(i)*gamer.names_per_lun]))
                lines.append('第%d轮' % i)
                lines.append('\n')
                lines.append('\t'.join(gamer.name_luck[(i-1)*gamer.names_per_lun:(i)*gamer.names_per_lun]))
                lines.append('\n')
            file.writelines(lines)
            file.close()
            showinfo(title='Hi', message='导出成功！')
        except:
            pass
        pass


class AppGamer:
    def __init__(self):
        self.current_lun = 1
        db = shelve.open('assets/game_init.db')
        names = db.get('names', '')
        lun_count = db.get('lun_count', 1)
        names_per_lun = db.get('names_per_lun', 1)
        names_per_line = db.get('names_per_line', 1)
        db.close()

        self.max_lun = lun_count
        self.names_per_lun = names_per_lun
        self.names_per_line = names_per_line

        self.name_all = []
        try:
            with open(names, 'r', encoding='utf-8') as f:
                for l in f.readlines():
                    people = l.rstrip()
                    self.name_all.append(people)
        except:
            pass
        self.name_luck = []
        self.name_left = self.name_all.copy()

    def get_lun(self):
        return self.current_lun

    def can_go_on(self):
        return self.current_lun <= self.max_lun

    def get_random_names(self):
        try:
            winners = random.sample(self.name_left, self.names_per_lun)
        except:
            winners = random.sample(self.name_all, self.names_per_lun)
        return winners

    def save_winner(self):
        winners = self.get_random_names()
        for winner in winners:
            print(winner)
            self.name_luck.append(winner)
            self.name_left.remove(winner)
        self.current_lun += 1
        return winners


class App(BigScreen):
    def __init__(self, the_title, ):
        super().__init__('assets/game_screen.toml')
        self.the_title = the_title
        self.export_file = 'assets/game_result.db'
        try:
            db = shelve.open(self.export_file)
            self.gamer = db.get('gamer', None)
            db.close()
        except:
            pass
        if self.gamer is None:
            self.gamer = AppGamer()
        pass

    def start_game(self):
        if self.game_paused and self.gamer.can_go_on():
            self.game_paused = False
            self.music_unpause()

    def pause_game(self):
        if not self.game_paused:
            self.game_paused = True
            self.music_pause()
            self.on_show()
            self.show_the_texts([self.the_title], self.conf['header'])
            self.show_the_texts(['第%d轮' % self.gamer.get_lun()], self.conf['lunci'])
            winners = self.gamer.save_winner()
            self.show_the_texts(winners, self.conf['row'])
            pygame.display.update()

    def on_mouse_wheel(self, event):
        pass

    def on_lbutton_down(self, event):
        self.start_game()
        pass

    def on_rbutton_down(self, event):
        self.pause_game()
        pass

    def on_other_key_down(self, key):
        if key == pygame.K_LCTRL:
            # 显示轮次
            self.gamer = AppGamer()
            db = shelve.open(self.export_file)
            db['gamer'] = self.gamer
            db.close()
            pass
        elif key == pygame.K_SPACE:
            # 开始
            self.start_game()
            pass
        elif key == pygame.K_RETURN:
            # 停
            self.pause_game()
            pass
        else:
            return
        # self.need_update = True

    def on_show(self):
        self._display_surf.blit(self.bg, (0, 0))
        pass

    def show_not_change(self):
        self._display_surf.blit(self.bg, (0, 0))
        self.show_the_texts([self.the_title], self.conf['header'])
        self.show_the_texts(['第%d轮' % self.gamer.get_lun()], self.conf['lunci'])
        self.show_the_texts(self.gamer.get_random_names(), self.conf['row'])

    def on_loop(self):
        self.show_not_change()
        pass

    def on_cleanup(self):
        db = shelve.open(self.export_file)
        db['gamer'] = self.gamer
        db.close()


if __name__ == '__main__':
    app = MyConfigApp()
    app.mainloop()
